<script setup lang="ts">
import { computed, ref, unref } from 'vue'
import { Checked, Edit, Refresh } from '@element-plus/icons-vue'
import { defaultCol } from '@/utils/custom'
import { useBaseApi, useBaseFileApi } from '@/api/base'
import { useMisApi } from '@/api/mis'
import { dayjs, ElLoading, ElMessage, type FormInstance } from 'element-plus'
import type { BusinessUIFile, BusinessUIFormType, DicType } from '@/types/custom'

import TemplateGridSelector from '@/views/components/grid/components/TemplateGridSelector.vue'
import TemplateAnnex from '@/views/components/form/components/TemplateAnnex.vue'

interface Props {
  uiForm?: BusinessUIFormType
  dicTable?: DicType[]
}

const props = defineProps<Props>()
const emit = defineEmits(['fetch'])

const {
  GetProducts,
  GetProductModels,
  GetStockItems,
  GetWarehouses,
  GetSmartShopOrder,
  GetUsUngOrder,
  GetUsUngShopOrder,
  GetMisItemList
} = useMisApi()
const { CustomRequest } = useBaseApi()
const { UploadBaseFile, UploadBaseImage } = useBaseFileApi()

// 业务选择器
const selectorRef = ref()
// 表单
const ruleFormRef = ref<FormInstance>()
// 弹窗
const formId = ref('')
const modal = ref(false)
const loading = ref(false)
const disabled = ref(false)
const params = ref<TypedAny>({})
// 产品
const productItems = ref<SelectOptionType[]>([])
// 型号
const productModelItems = ref<SelectOptionType[]>([])
// 项目
const whItems = ref<SelectOptionType[]>([])
// MIS项目
const misItems = ref<SelectOptionType[]>([])
// 仓库
const warehouseItems = ref<SelectOptionType[]>([])
// 订单信息
const orderInfos = ref<SelectOptionType[]>([])
// 是否是入库
const isSoldOut = computed(() => params.value.set_type === '0')
// 是否是出库
const isSell = computed(() => params.value.set_type === '1')
const orders_ids: TypedAny = {
  '0': 'ec3500c2-5908-46a1-9ce3-13d277848bc8',
  '1': '0524ffa8-f333-45c9-b128-3346cb7e2133',
  '5': '78b4bd12-be88-4c74-b926-a6a60ca3981e'
}
// 订单业务id
const order_business_id = computed(() => {
  return orders_ids[params.value.out_set_type] || ''
})

const submitForm = (isClose?: boolean) => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      handleSave(isClose)
    }
  })
}

const handleSave = async (isClose?: boolean) => {
  if (!props.uiForm) return Promise.reject(false)
  const { api } = props.uiForm

  const dataParams: any = unref(params)

  loading.value = true

  try {
    // 上传附件
    await handleUpload(dataParams, 'custom-annex')

    // // 上传图片
    // await handleUpload(dataParams, 'custom-image')

    const { data } = await CustomRequest({
      url: api,
      method: 'post',
      data: dataParams
    })
    if (data.id) {
      formId.value = data.id
      await onFetch()
    }
    ElMessage.success('保存成功')
    emit('fetch')
    loading.value = false
    if (isClose) modal.value = false
  } catch (e) {
    loading.value = false
  }
}

/**
 * 单个批量上传（为了保留idx排序）
 * @param list
 * @param key
 */
const handleBatchUpload = async (list: BusinessUIFile[], key: string) => {
  const result: BusinessUIFile[] = []
  for (let i = 0; i < list.length; i++) {
    let res
    if (key === 'custom-image') {
      res = await UploadBaseImage(list[i])
    } else {
      res = await UploadBaseFile(list[i])
    }
    if (res.data.length) {
      res.data[0].idx = list[i].idx
      result.push(res.data[0])
    }
  }
  return result
}

/**
 * 上传附件或者图片
 * @param dataParams
 * @param key
 */
const handleUpload = async (dataParams: TypedAny, key: string = 'custom-annex') => {
  const option: any = {
    'custom-annex': 'files',
    'custom-image': 'imgs'
  }
  const field: string = option[key]
  if (field) {
    const files: BusinessUIFile[] = dataParams[field] || []
    files.forEach((v, idx) => {
      v.idx = idx
    })
    const newFiles = files.filter((f) => f.raw)
    const oldFiles = files.filter((f) => !f.raw)
    if (newFiles.length) {
      const result = await handleBatchUpload(newFiles, key)
      dataParams[field] = oldFiles.concat(result)
    } else {
      dataParams[field] = files
    }
  }
}

/**
 * 产品
 */
const fetchProducts = async () => {
  const { data } = await GetProducts<ApiSelectOption[]>()
  productItems.value = data.map((v) => {
    return {
      label: v.name,
      value: v.id,
      idx: v.idx
    }
  })
  await fetchProductModels()
}

/**
 * 产品型号
 */
const fetchProductModels = async () => {
  const product_id = params.value.product_id
  const { data } = await GetProductModels<ApiSelectOption[]>({ product_id })
  if (params.value.product_model_id && !data.some((s) => s.id === params.value.product_model_id))
    params.value.product_model_id = ''
  productModelItems.value = data.map((v) => {
    return {
      label: v.name,
      value: v.id,
      idx: v.idx
    }
  })
}

/**
 * 产品型号
 */
const fetchWarehouses = async () => {
  const { data } = await GetWarehouses<ApiSelectOption[]>({ product_id: params.value.product_id })
  warehouseItems.value = data.map((v) => {
    return {
      label: v.name,
      value: v.id,
      idx: v.idx
    }
  })
}

/**
 * 库存分类
 */
const fetchStockItems = async () => {
  const { data } = await GetStockItems<ApiSelectOption[]>()
  whItems.value = data.map((v) => {
    return {
      label: v.name,
      value: v.id,
      idx: v.idx
    }
  })
}

/**
 * MIS项目
 */
const fetchMisItemList = async () => {
  const { data } = await GetMisItemList<ApiSelectOption[]>()
  misItems.value = data.map((v) => {
    return {
      label: v.name,
      value: v.id,
      idx: v.idx
    }
  })
}

/**
 * 查询详情
 * @param id
 */
const fetchDetail = async (id: string) => {
  if (!props.uiForm) return Promise.reject('未配置表单接口')
  loading.value = true
  const { api } = props.uiForm
  return CustomRequest<TypedAny>({
    url: api,
    method: 'get',
    params: { id }
  }).finally(() => {
    loading.value = false
  })
}

const onFetch = async () => {
  const id = unref(formId)
  const { data } = await fetchDetail(id)
  data.diff = data.qty - data.stock_qty
  data.files = data.files || []
  params.value = data || {}
  await fetchProductModels()
  fetchOrder()
}

/**
 * 出入库编辑/新增入库
 */
const handleSoldOut = async (set_type: string, row?: TypedAny) => {
  if (row) {
    formId.value = row.id
    const loadingInstance = ElLoading.service({ text: '加载中', background: 'rgba(0,0,0,0)' })
    try {
      await onFetch()
      loadingInstance.close()
    } catch (e) {
      loadingInstance.close()
    }
  } else {
    formId.value = ''
    params.value = { set_type, set_date: dayjs().format('YYYY-MM-DD') }
  }
  modal.value = true
}

/**
 * 新增出库
 */
const handleSell = async (set_type: string, row?: TypedAny) => {
  params.value = {}
  if (row && row.id) {
    params.value.set_type = set_type
    params.value.set_date = dayjs().format('YYYY-MM-DD')
    const loadingInstance = ElLoading.service({ text: '加载中', background: 'rgba(0,0,0,0)' })
    try {
      const { data } = await fetchDetail(row.id)
      params.value.diff = data.qty - data.stock_qty
      params.value.warehouse_id = data.warehouse_id
      params.value.product_id = data.product_id
      params.value.product_model_id = data.product_model_id
      params.value.wh_item_id = data.wh_item_id
      params.value.price = data.price
      params.value.unit = data.unit
      params.value.total_amount = data.total_amount
      params.value.received_amount = data.received_amount
      params.value.mf_date = data.mf_date
      params.value.ex_date = data.ex_date
      params.value.ex_month = data.ex_month
      params.value.stock_in_id = data.id
      params.value.files = []
      onInitDefault()
      loadingInstance.close()
      modal.value = true
    } catch (e) {
      loadingInstance.close()
    }
  } else {
    ElMessage.warning('请选择入库单')
  }
}

const open = (set_type: string, row?: TypedAny) => {
  switch (set_type) {
    case '0':
      handleSoldOut(set_type, row)
      onInitDefault()
      break
    case '1':
      handleSell(set_type, row)
      break
  }
}

const onOutChange = () => {
  orderInfos.value = []
}

// const clearValidate = async () => {
//   await nextTick()
//   ruleFormRef.value?.clearValidate()
// }

/**
 * 是否是分组
 */
const getFormRules = (title: string) => {
  return [{ required: true, message: `请输入${title}`, trigger: 'change' }]
}

/**
 * 获取字典
 * @param key
 */
const getDicOptions = (key: string) => {
  const dicTable = props.dicTable || []
  return dicTable
    .filter((f) => f.column_name === key)
    .map((v) => {
      return {
        label: v.display_text,
        value: v.value_text
      }
    })
}

const openModal = () => {
  selectorRef.value.open()
}

const onRemoveOrder = () => {
  params.value.out_order_detail_id = undefined
  orderInfos.value = []
}

const handleConfirm = (id: string) => {
  params.value.out_order_detail_id = id
  fetchOrder()
}

const fetchOrder = () => {
  const { out_order_detail_id, out_set_type } = unref(params)
  if (out_order_detail_id) {
    // ['0', '1', '5']
    if (out_set_type === '0') {
      GetSmartShopOrder({ out_order_detail_id }).then(({ data }) => {
        const { selected } = data
        formatOrderInfo(selected)
      })
    } else if (out_set_type === '1') {
      GetUsUngOrder({ out_order_detail_id }).then(({ data }) => {
        const { selected } = data
        formatOrderInfo(selected)
      })
    } else if (out_set_type === '5') {
      GetUsUngShopOrder({ out_order_detail_id }).then(({ data }) => {
        const { selected } = data
        formatOrderInfo(selected)
      })
    }
  }
}

const formatOrderInfo = (selected: TypedAny[]) => {
  if (selected.length) {
    const info = selected[0]
    const keys: TypedAny = {
      // 微信商城
      product_name: '产品名称',
      order_user: '订单用户',
      address: '收货地址',
      num: '数量',
      // U上商城
      good_name: '产品名称',
      // 公用
      amount: '数量',
      price: '单价',
      link_man: '联系人',
      link_phone: '联系方式'
    }
    const list: SelectOptionType[] = []
    for (const k in info) {
      const value = info[k]
      const label = keys[k]
      if (value !== null && label) {
        list.push({
          label: label,
          value: info[k]
        })
      }
    }
    orderInfos.value = list
  } else {
    orderInfos.value = []
  }
}

/**
 * 获取默认数据（产品，库存分类，mis项目，产品规格等）
 */
const onInitDefault = () => {
  fetchProducts()
  fetchStockItems()
  fetchMisItemList()
  fetchWarehouses()
}

defineExpose({ open })
</script>

<template>
  <vxe-modal
    show-zoom
    :show-minimize="false"
    :dblclick-zoom="false"
    resize
    v-model="modal"
    width="90%"
    height="90%"
    destroy-on-close
    class-name="custom-modal"
  >
    <template #title>
      <el-button
        type="primary"
        @click.stop="submitForm()"
        :loading="loading"
        :icon="Edit"
        v-if="!disabled"
      >
        保存
      </el-button>
      <el-button
        type="warning"
        @click.stop="submitForm(true)"
        :loading="loading"
        :icon="Edit"
        v-if="!disabled"
        class="ml5"
      >
        保存并关闭
      </el-button>
      <el-button
        @click.stop="onFetch"
        :loading="loading"
        :icon="Refresh"
        class="ml5"
        v-if="params.id"
      >
        刷新
      </el-button>
      <el-button @click="modal = false" class="ml5">关闭</el-button>
    </template>
    <el-form
      ref="ruleFormRef"
      :model="params"
      label-width="auto"
      label-position="top"
      class="mx10 my5"
    >
      <el-row :gutter="10">
        <el-col :span="24" class="mb5">
          <!--disabled-->
          <el-radio-group v-model="params.set_type" disabled>
            <el-radio-button label="入库单" value="0" />
            <el-radio-button label="出库单" value="1" />
          </el-radio-group>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="仓库" prop="warehouse_id" required :rules="getFormRules('仓库')">
            <el-select
              placeholder="请选择仓库"
              v-model="params.warehouse_id"
              class="w100"
              @change="fetchProductModels"
              clearable
              filterable
              :disabled="isSell || (isSoldOut && !!params.id)"
            >
              <el-option
                v-for="(option, index) in warehouseItems"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="产品" prop="product_id" required :rules="getFormRules('产品')">
            <el-select
              placeholder="请选择产品"
              v-model="params.product_id"
              class="w100"
              @change="fetchProductModels"
              clearable
              filterable
              :disabled="isSell || (isSoldOut && !!params.id)"
            >
              <el-option
                v-for="(option, index) in productItems"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="型号" prop="product_model_id" required :rules="getFormRules('型号')">
            <el-select
              placeholder="请选择型号"
              v-model="params.product_model_id"
              class="w100"
              clearable
              :disabled="isSell || (isSoldOut && !!params.id)"
            >
              <el-option
                v-for="(option, index) in productModelItems"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--类型/项目-->
        <el-col :span="24" class="mb5">
          <el-divider content-position="left" border-style="dashed">类型/项目</el-divider>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="库存类型" prop="wh_item_id">
            <el-select
              placeholder="请选择库存类型"
              v-model="params.wh_item_id"
              class="w100"
              clearable
              filterable
            >
              <el-option
                v-for="(option, index) in whItems"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="MIS项目" prop="mis_item_id">
            <el-select
              placeholder="请选择MIS项目"
              v-model="params.mis_item_id"
              class="w100"
              clearable
              filterable
            >
              <el-option
                v-for="(option, index) in misItems"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!--量-->
        <el-col :span="24" class="mb5">
          <el-divider content-position="left" border-style="dashed">
            {{ params.set_type === '0' ? '入库量' : '出库量' }}
          </el-divider>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item
            :label="params.set_type === '0' ? '入库数量' : '出库数量'"
            prop="qty"
            required
            :rules="getFormRules(params.set_type === '0' ? '入库数量' : '出库数量')"
          >
            <el-input-number v-model="params.qty" class="w100" />
          </el-form-item>
        </el-col>
        <!--        <el-col v-bind="defaultCol" v-if="params.diff">-->
        <!--          <div class="flex align-end h100 pb3 color-danger">-->
        <!--            <span>剩余量：{{ params.diff }}</span>-->
        <!--          </div>-->
        <!--        </el-col>-->

        <!--出库明细-->
        <el-col :span="24" class="mb5">
          <el-divider content-position="left" border-style="dashed">
            {{ params.set_type === '0' ? '入库明细' : '出库明细' }}
          </el-divider>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item
            :label="params.set_type === '0' ? '入库日期' : '出库日期'"
            prop="set_date"
            required
            :rules="getFormRules(params.set_type === '0' ? '入库日期' : '出库日期')"
          >
            <el-date-picker
              class="w100"
              placeholder="请选择日期"
              type="date"
              v-model="params.set_date"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-if="isSell" v-bind="defaultCol">
          <el-form-item
            label="出库类型"
            prop="out_set_type"
            required
            :rules="getFormRules('出库类型')"
          >
            <el-select
              placeholder="请选择出库类型"
              v-model="params.out_set_type"
              class="w100"
              @change="onOutChange"
            >
              <el-option
                v-for="(option, index) in getDicOptions('out_set_type')"
                :key="index"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="['0', '1', '5'].includes(params.out_set_type)" :span="24">
          <el-form-item
            label="关联订单"
            prop="out_order_detail_id"
            required
            :rules="getFormRules('关联订单')"
          >
            <div class="w100">
              <el-space :size="5">
                <el-button :icon="Checked" @click="openModal" type="primary" plain>
                  {{ orderInfos.length ? '切换订单' : '选择订单' }}
                </el-button>
                <el-button
                  :icon="Checked"
                  @click="onRemoveOrder"
                  type="danger"
                  plain
                  :disabled="!orderInfos.length"
                >
                  移除订单
                </el-button>
              </el-space>
              <el-descriptions v-if="orderInfos.length" border class="mt5">
                <el-descriptions-item
                  v-for="(order, idx) in orderInfos"
                  :key="idx"
                  :label="order.label"
                >
                  {{ order.value }}
                </el-descriptions-item>
              </el-descriptions>
              <!--              <el-empty-->
              <!--                v-else-->
              <!--                :image-size="24"-->
              <!--                description="未选择关联订单"-->
              <!--                class="pa0"-->
              <!--              />-->
            </div>
          </el-form-item>
        </el-col>
        <el-col v-else :span="24">
          <el-form-item label="关联订单" prop="out_order_detail_id">
            <el-input v-model="params.out_order_detail_id" placeholder="输入关联订单" clearable />
          </el-form-item>
        </el-col>

        <!--产品详情-->
        <el-col :span="24" class="my5">
          <el-divider content-position="left" border-style="dashed">产品详情</el-divider>
        </el-col>

        <el-col v-bind="defaultCol">
          <el-form-item label="单价" prop="price">
            <el-input-number :disabled="isSell" v-model="params.price" class="w100" />
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="单位" prop="unit">
            <el-input
              :disabled="isSell"
              v-model="params.unit"
              class="w100"
              placeholder="请输入单位"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="应付总价" prop="total_amount">
            <el-input-number :disabled="isSell" v-model="params.total_amount" class="w100" />
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="已付总价" prop="received_amount">
            <el-input-number :disabled="isSell" v-model="params.received_amount" class="w100" />
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="生产日期" prop="mf_date">
            <el-date-picker
              class="w100"
              placeholder="请选择生产日期"
              type="date"
              v-model="params.mf_date"
              value-format="YYYY-MM-DD"
              :disabled="isSell"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="过期日期" prop="ex_date">
            <el-date-picker
              class="w100"
              placeholder="请选择过期日期"
              type="date"
              v-model="params.ex_date"
              value-format="YYYY-MM-DD"
              :disabled="isSell"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-bind="defaultCol">
          <el-form-item label="保质期（月）" prop="ex_month">
            <el-input-number :disabled="isSell" v-model="params.ex_month" class="w100" />
          </el-form-item>
        </el-col>

        <!--其他信息-->
        <el-col :span="24" class="my5">
          <el-divider content-position="left" border-style="dashed">其他信息</el-divider>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="params.remark"
              :rows="2"
              type="textarea"
              placeholder="请输入备注"
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="结算备注" prop="balance_info">
            <el-input
              v-model="params.balance_info"
              :rows="2"
              type="textarea"
              placeholder="请输入结算备注"
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mt10">
          <el-form-item prop="files">
            <TemplateAnnex v-model="params.files" title="附件" :disabled="disabled" class="w100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <TemplateGridSelector
      ref="selectorRef"
      :business_id="order_business_id"
      @confirm="handleConfirm"
    />
  </vxe-modal>
</template>
